//
//  YWMaterialStockOutWithNoScanTVC.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/5/19.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWMaterialStockOutWithNoScanTVC.h"
#import "Masonry.h"
#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"

#import "YWSelectContactTableViewController.h"
#import "YWSelectMaterialTableViewController.h"
#import "YWSelectBuildingTableViewController.h"

//#import "YWWriteNoteCell.h"
#import "YWSelectPersonTableViewCell.h"
#import "YWMaterialAddOrSubTableViewCell.h"

#import "YWHandler.h"
#import "YWConst.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWMaterialManager.h"
#import "YWMaterialStock.h"
#import "YWMaterialApply.h"
#import "YWMaterialApplyDetail.h"
#import "YWMaterialStockOut.h"
#import "YWMaterialStockOutDetail.h"
#import "YWMaterialReturn.h"
#import "YWMaterialReturnDetail.h"

@interface YWMaterialStockOutWithNoScanTVC ()<YWSelectPersonTableViewCellDelegate,YWContactVCSelectContactDelegate>

@property (nonatomic, strong) YWBuilding *building;
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) NSMutableArray * receiveContacts;
@property (nonatomic, strong) NSMutableArray * materialArray;
@property (nonatomic, assign) NSInteger currentSelectTag;
@property (nonatomic, strong) YWHandler *handler;
@end

@implementation YWMaterialStockOutWithNoScanTVC

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = _isApplySure ? @"物料出库" : @"物料入库";
    [self setupMaterialData];
    [self setupTableView];
}

- (void)setupMaterialData{
    if (_isApplySure) {
//        [self.apply.details enumerateObjectsUsingBlock:^(YWMaterialApplyDetail*  _Nonnull applyDetail, NSUInteger idx, BOOL * _Nonnull stop) {
//            applyDetail.materialStock.selectQuantity = applyDetail.quantity;
//            [tempMaterialArray addObject:applyDetail.materialStock];
//        }];
        [self.materialArray addObjectsFromArray:self.stockOut.details];
        self.handler = self.stockOut.receiver;
    }else{
//        [self.stockOut.details enumerateObjectsUsingBlock:^(YWMaterialStockOutDetail *  _Nonnull stockOutDetail, NSUInteger idx, BOOL * _Nonnull stop) {
//            stockOutDetail.materialStock.selectQuantity = stockOutDetail.quantity;
//            [tempMaterialArray addObject:stockOutDetail.materialStock];
//        }];
        [self.materialArray addObjectsFromArray:self.retrunBack.details];
        self.handler = self.retrunBack.creator;
    }
//    self.materialArray = tempMaterialArray;
}

- (void)setupTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView registerClass:[YWSelectPersonTableViewCell class] forCellReuseIdentifier:YWSelectPersonTableViewCellIdentifier];
    [self.tableView registerClass:[YWMaterialAddOrSubTableViewCell class] forCellReuseIdentifier:YWMaterialAddOrSubTableViewCellIdentifier];
    self.tableView.tableFooterView = self.footView;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)materialArray{
    if (!_materialArray) {
        _materialArray = [NSMutableArray array];
    }
    return _materialArray;
}

-(YWBuilding *)building{
    if (!_building) {
        if (_isApplySure) {//出库
            YWMaterialStockOutDetail *stockOutDetail = self.materialArray[0];
            YWBuilding * building = [[YWBuildingManager shareManager] buildingWithId:stockOutDetail.materialStock.buildingId];
            _building = building;
        }else{//入库
            YWMaterialReturnDetail *returnBackDetail = self.materialArray[0];
            YWBuilding * building = [[YWBuildingManager shareManager] buildingWithId:returnBackDetail.materialStock.buildingId];
            _building = building;
        }
    }
    return _building;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 1 ? [self.materialArray count]+1:1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"YWMaterialStockOutWithNoScanTVCIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = self.handler.userName;
        return cell;
    }else{
        static NSString *identifier = @"YWMaterialStockOutWithNoScanTVCIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = @"名称";
            cell.textLabel.textColor = [UIColor customTextGrayColor];
            cell.textLabel.font = kContentFont;
            cell.detailTextLabel.text = @"数量";
            cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
            cell.detailTextLabel.font = kContentFont;
            return cell;
        }else{
            YWMaterialAddOrSubTableViewCell * materialCell = [tableView dequeueReusableCellWithIdentifier:YWMaterialAddOrSubTableViewCellIdentifier];
            if (_isApplySure) {
                materialCell.stockOutDetail = self.materialArray[indexPath.row-1];
            }else{
                materialCell.returnDetail = self.materialArray[indexPath.row-1];
            }
            return materialCell;
        }
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        YWSelectContactTableViewController *contactVC = [[YWSelectContactTableViewController alloc] init];
        contactVC.delegate = self;
        contactVC.buildingId = self.building.buildingId;
        contactVC.isMultiSelect = NO;
        contactVC.ownContacts = self.handler ? @[self.handler] : nil;
        contactVC.titleName = _isApplySure ? @"选择领用人" : @"选择接收人";
        [self.navigationController pushViewController:contactVC animated:YES];
    }
}

#pragma mark - YWContactVCSelectContactDelegate
-(void)selectSingleContact:(YWHandler *)contact{
    _handler = contact;
    [self.tableView reloadData];
}

#pragma mark - tableView section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWMaterialStockOutWithNoScanTVCForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, (SCREEN_WIDTH - 2 * 15), 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return _isApplySure ? @"物料领用人" : @"物料接收人";
    }else{
        return @"物料清单";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickCommitButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

- (void)clickCommitButton:(UIButton *)sender{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:_isApplySure?@"出库确认":@"入库确认" message:_isApplySure?@"您确定出库吗?":@"您确定入库吗?" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (_isApplySure) {
            [self submitCreateMaterialStockOut];
        }else{
            [self submitCreateMaterialReturnBack];
        }
    }]];
}

- (void)submitCreateMaterialStockOut
{
    [self.view endEditing:YES];
    [self.HUD show:YES];
    [[YWMaterialManager shareManager] postMaterialStockOutCerturnWithReceiver:_handler stockOut:_stockOut WithComplete:^(BOOL success) {
        if (success) {
            //发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMaterialNoScanSureNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"出库失败,请稍后重试"];
        }
    }];
}

- (void)submitCreateMaterialReturnBack{
    [self.view endEditing:YES];
    [self.HUD show:YES];
    [[YWMaterialManager shareManager] postMaterialReturnBackCerturnWithCreator:_handler returnBack:_retrunBack  WithComplete:^(BOOL success) {
        if (success) {
            //发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMaterialNoScanSureNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"出库失败,请稍后重试"];
        }
    }];
}

- (MBProgressHUD*)HUD{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

@end
